﻿using System;
using System.Web;
using SmartContentModule.CssModel;
using SmartContentModule.Helpers;
using SmartContentModule.VersionManagement;

namespace SmartContentModule
{
    public class ContentModule : IHttpModule
    {
        private const int refreshWorkerInterval = 60;//todo webconfig

        public delegate void SCMExceptionHandler(object sender, SCMException ex);

        public static SCMExceptionHandler HandleSCMException;

        /// <summary>
        /// Clean resources
        /// </summary>
        public void Dispose()
        {

        }

        /// <summary>
        /// This property is set to true on Init method.
        /// Used to check if module is enabled
        /// </summary>
        public static bool Enabled
        {
            get;
            set;
        }

        /// <summary>
        /// Set true on first init, so prevent multiple restart of refresh worker
        /// </summary>
        private static bool FirstInitCompleted
        {
            get;
            set;
        }

        /// <summary>
        /// Initialize, register events, clear temp folder and activate content refresh thread
        /// </summary>
        /// <param name="context">HttpApplication</param>
        public void Init(HttpApplication context)
        {
            Enabled = true;
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.Error += new EventHandler(context_Error);
            if (!FirstInitCompleted)
            {
                lock (typeof(ContentModule))
                {
                    if (!FirstInitCompleted)
                    {
                        FirstInitCompleted = true;
                        IOHelper.ClearVBTempFolder();
                        CssFileInfoRefreshWorker.Instance.Initialize(refreshWorkerInterval);
                    }
                }
            }
        }

        void context_Error(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            ExceptionHelper.HandleError(String.Empty, context.Error);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

            if (app.Request.Url.AbsolutePath.ToLowerInvariant().EndsWith(".css.axd"))
            {
                string target = context.Request.QueryString["Target"];
                if (String.IsNullOrEmpty(target))
                    return;

                try
                {
                    string cssTempFilePath = GetFilePathFromTarget(target);
                    if (String.IsNullOrEmpty(cssTempFilePath))
                        return;

                    context.Response.ContentType = "text/css";
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    context.Response.ExpiresAbsolute = DateTime.Today.AddYears(1);
                    context.Response.WriteFile(cssTempFilePath);
                }
                catch (Exception ex)
                {
                    //log error and return original css
                    ExceptionHelper.HandleError(String.Empty, ex);
                    context.Response.Write(app.Request.Url.AbsolutePath.ToLowerInvariant().Replace(".axd", String.Empty));
                }
                app.CompleteRequest();
            }

        }

        private string GetFilePathFromTarget(string target)
        {
            return VersionManager.GetContentFilePathForVersion(target);
        }

    }
}
